<template>
  <el-card style="padding: 20px">
    <el-form ref="formRef" :model="form" inline>
      <el-form-item
        v-for="(
          { form_item_json: { label, prop }, component_name, component_json },
          index
        ) in form_json"
        :key="index"
        v-bind="{ label, prop }"
      >
        <component
          :is="component_name"
          v-model="form[prop]"
          v-bind="component_json"
        >
          <template v-if="component_name === 'el-select'">
            <el-option
              v-for="(i, v) in component_json.option_data"
              :key="v"
              v-bind="i"
            ></el-option>
          </template>
        </component>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-search"
          @click="get_list"
          >搜索</el-button
        >
        <el-button size="mini" icon="el-icon-refresh" @click="reset"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <div class="function" style="margin-bottom: 20px">
      <el-button
        @click="handle_add"
        size="mini"
        type="primary"
        icon="el-icon-plus"
        plain
        >新增</el-button
      >
      <el-button
        :disabled="ids.length !== 1"
        size="mini"
        type="success"
        icon="el-icon-edit"
        plain
        @click="handle_edit(ids[0])"
        >修改</el-button
      >

      <el-button
        :disabled="!ids.length"
        size="mini"
        type="danger"
        icon="el-icon-delete"
        plain
        @click="handle_del(ids)"
        >删除</el-button
      >
      <el-button
        disabled
        size="mini"
        type="warning"
        icon="el-icon-download"
        plain
        >导出</el-button
      >
    </div>
    <el-table :data="list" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection"></el-table-column>
      <el-table-column v-slot="scope" label="头像">
        <el-image
          style="height: 60px; width: 60px"
          :src="getUrl(scope.row.avatar)"
        ></el-image>
      </el-table-column>
      <el-table-column
        v-for="(item, index) in list_json"
        :key="index"
        v-bind="item"
      >
        <template v-if="item.prop === 'isAdmin'" v-slot="scope">
          <el-switch
            v-model="scope.row.isAdmin"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" v-slot="scope">
        <el-button
          size="mini"
          type="text"
          icon="el-icon-edit"
          @click="handle_edit(scope.row.id)"
          >修改</el-button
        >
        <el-button
          size="mini"
          type="text"
          icon="el-icon-setting"
          @click="
            visible_password = true;
            form_edit_password.userId = scope.row.id;
          "
          >重置密码</el-button
        >
        <el-button
          size="mini"
          type="text"
          icon="el-icon-bank-card"
          @click="handle_reset(scope.row)"
          >充值</el-button
        >
        <el-button
          size="mini"
          type="text"
          icon="el-icon-delete"
          @click="handle_del(scope.row.id)"
          >删除</el-button
        >
      </el-table-column>
    </el-table>
    <el-pagination
      style="text-align: right; margin-top: 20px"
      background
      @size-change="
        (val) => {
          this.pager.pageSize = val;
          this.get_list();
        }
      "
      @current-change="
        (val) => {
          this.pager.pageNum = val;
          this.get_list();
        }
      "
      :current-page="pager.pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pager.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pager.totalRow"
    >
    </el-pagination>
    <el-dialog
      :title="title"
      :visible="visible"
      width="30%"
      @close="close"
      @closed="llq"
    >
      <el-form
        ref="formEditRef"
        :model="form_edit"
        label-width="80px"
        :rules="rules"
      >
        <template
          v-for="(
            {
              form_item_json: { label, prop },
              component_name,
              component_json,
              isShow,
            },
            index
          ) in form_edit_json"
        >
          <el-form-item
            :key="index"
            v-if="is_add || isShow"
            v-bind="{ label, prop }"
          >
            <component
              :is="component_name"
              v-model="form_edit[prop]"
              v-bind="component_json"
            >
              <template v-if="component_name === 'el-select'">
                <el-option
                  v-for="(i, v) in component_json.option_data"
                  :key="v"
                  v-bind="i"
                ></el-option>
              </template>
            </component>
          </el-form-item>
        </template>

        <el-form-item label="用户头像">
          <el-upload
            :headers="uploadHeaders"
            action="http://8.138.102.145/api/upload/avatar"
            list-type="picture-card"
            :limit="1"
            :file-list="file_list"
            :on-success="handle_success"
            :on-exceed="on_exceed"
            accept="jpg,png,jpeg"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button type="primary" size="mini" @click="submit">确定</el-button>
          <el-button size="mini" @click="visible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      title="重置密码"
      :visible="visible_password"
      width="20%"
      @close="
        visible_password = false;
        form_edit_password.password = '';
      "
    >
      <el-form :model="form_edit_password">
        <el-form-item>
          <el-input
            placeholder="密码"
            v-model="form_edit_password.password"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button type="primary" size="mini" @click="reset_password"
            >确定</el-button
          >
          <el-button size="mini" @click="visible_password = false"
            >取消</el-button
          >
        </div>
      </template>
    </el-dialog>
    <el-dialog
      width="300px"
      center
      title="充值"
      :visible.sync="llqshow"
      @close="cz_obj.cz = 0"
    >
      <el-form :model="cz_obj" inline>
        <el-form-item label="当前余额">
          {{ cz_obj.balance || 0 }}
        </el-form-item>
        <el-form-item label="充值金额">
          <el-input-number
            size="mini"
            :min="1"
            v-model="cz_obj.amount"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            size="mini"
            type="password"
            v-model="cz_obj.password"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="handle_cz">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>
import { omit } from "lodash";
export default {
  mounted() {
    

    this.get_list();
    const token = sessionStorage.getItem("token");
    if (token) {
      this.uploadHeaders.Authorization = `${token}`;
    }
    this.$http.get("/auth/userinfo").then((res) => {
      this.userId = res.data.id;
    });
  },
  data() {
    return {
      llqshow: false,
      cz_obj: {
        balance: 0,
        cz: 0,
      },
      userId: 0,
      uploadHeaders: {},
      ids: [],
      form_edit_password: {},
      pager: {
        pageNum: 1,
        pageSize: 10,
        totalRow: 0,
      },
      list: [],
      list_json: [
        { label: "用户名", prop: "nickName" },
        { label: "账号", prop: "username" },
      ],
      form: {
        nickName: "",
        isAdmin: "",
      },
      form_json: [
        {
          form_item_json: { label: "用户名", prop: "nickName" },
          component_name: "el-input",
          component_json: { placeholder: "用户名", size: "small" },
        },
        {
          form_item_json: { label: "管理员", prop: "isAdmin" },
          component_name: "el-select",
          component_json: {
            placeholder: "管理员",
            size: "small",
            option_data: [
              { label: "管理员", value: 1 },
              { label: "普通用户", value: 0 },
            ],
          },
        },
      ],
      form_edit: {
        isAdmin: "",
        password: "",
        nickName: "",
        username: "",
      },
      visible_password: false,
      form_edit_json: [
        {
          isShow: true,
          form_item_json: { label: "用户名", prop: "nickName" },
          component_name: "el-input",
          component_json: { placeholder: "用户名", size: "small" },
        },
        {
          isShow: false,
          form_item_json: { label: "账号", prop: "username" },
          component_name: "el-input",
          component_json: { placeholder: "账号", size: "small" },
        },
        {
          isShow: false,
          form_item_json: { label: "密码", prop: "password" },
          component_name: "el-input",
          component_json: {
            type: "password",
            placeholder: "密码",
            size: "small",
          },
        },
        {
          isShow: true,
          form_item_json: { label: "管理员", prop: "isAdmin" },
          component_name: "el-select",
          component_json: {
            placeholder: "管理员",
            size: "small",
            option_data: [
              { label: "管理员", value: 1 },
              { label: "普通用户", value: 0 },
            ],
          },
        },
      ],
      title: "",
      visible: false,
      rules: {
        nickName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        username: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      is_add: false,
      file_list: [],
    };
  },
  methods: {
    get_list() {
      this.$http
        .get("/user", {
          params: {
            ...this.pager,
            ...this.form,
          },
        })
        .then((res) => {
          this.list = res.rows;
          this.pager = omit(res, ["msg", "status", "rows"]);
        });
    },
    reset() {
      this.$refs.formRef.resetFields();
      this.get_list();
    },
    handleSelectionChange(val) {
      this.ids = val.map((v) => v.id);
    },
    handle_add() {
      this.visible = true;
      this.title = "添加用户";
      this.is_add = true;
    },
    handle_edit(id) {
      this.visible = true;
      this.title = "修改用户";
      this.is_add = false;
      this.file_list = [
        {
          url:
            "http://8.138.102.145:8232/images/" +
            this.list.find((v) => v.id == id).avatar,
        },
      ];
      Object.assign(
        this.form_edit,
        this.list.find((v) => v.id == id)
      );
    },
    handle_del(id) {
      if (id == this.userId) {
        return this.$message.warning("你删自己干嘛，有病啊？");
      }
      this.$confirm("是否确认删除用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http.delete(`/user${this.getIds(id)}`).then((res) => {
            if (res.status === 200) {
              this.$message.success(res.msg);
              this.get_list();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    submit() {
      this.$refs.formEditRef.validate((callback) => {
        if (callback) {
          if (this.is_add) {
            this.$http.post("/user", this.form_edit).then((res) => {
              if (res.status === 200) {
                this.$message.success(res.msg);
                this.visible = false;
                this.get_list();
              }
            });
          } else {
            const from = this.form_edit;
            delete from.password;
            this.$http.put("/user", from).then((res) => {
              if (res.status === 200) {
                this.$message.success(res.msg);
                this.visible = false;
                this.get_list();
              }
            });
          }
        }
      });
    },
    getUrl(avatar) {
      return "http://8.138.102.145:8232/images/" + avatar;
    },
    close() {
      this.$refs.formEditRef.resetFields();
      this.form_edit = {
        name: "",
        username: "",
        isAdmin: "",
        nickName: "",
      };
      this.visible = false;
    },
    getIds(ids) {
      if (Array.isArray(ids)) {
        if (ids.length > 0) {
          const params = new URLSearchParams();
          ids.forEach((id) => {
            params.append("id", id);
          });
          ids = params.toString();
        } else {
          ids = "";
        }
        return `?${ids}`;
      } else {
        return `?id=${ids}`;
      }
    },
    on_exceed() {
      this.$message.warning("只能上传一张图片");
    },
    llq() {
      this.file_list = [];
    },
    handle_success(file) {
      this.form_edit.avatar = file.data;
    },
    reset_password() {
      this.$http
        .post("/user/resetPwd", {
          ...this.form_edit_password,
          newPassword: this.form_edit_password.password,
        })
        .then((res) => {
          if (res.status === 200) {
            this.$message.success(res.msg);
            this.visible_password = false;
            this.get_list();
          }
        });
    },
    handle_reset(row) {
      console.log(row);
      this.llqshow = true;
      this.cz_obj = {
        userId: row.id,
        amount: 0,
        balance: row.balance,
        password: "",
      };
    },
    handle_cz() {
      this.$http.post("/user/exchange", this.cz_obj).then((res) => {
        if (res.status === 200) {
          this.get_list();
          this.$message.success("充值成功");
          this.llqshow = false;
        } else {
          this.$message.success(res.msg);
          this.llqshow = false;
        }
      });
    },
  },
};
</script>

<style style="scss">
.el-table__header th {
  background-color: #f8f8f9 !important;
  color: #515a6e;
}
</style>
